<?php
namespace app\controller;

use app\service\MqttClient;
use think\Controller;
use think\facade\Config;

class Mqtt extends Controller
{
    /**
     * 发布MQTT消息
     */
    public function publish()
    {
        // 获取参数
        $topic = $this->request->param('topic', 'test/tp5');
        $message = $this->request->param('message', '');
        $qos = (int)$this->request->param('qos', 0);
        
        if (empty($message)) {
            return json(['code' => 0, 'msg' => '消息内容不能为空']);
        }
        
        // 获取MQTT配置
        $config = Config::get('mqtt.');
        
        try {
            // 创建MQTT客户端
            $mqtt = new MqttClient($config);
            
            // 连接到MQTT服务器
            if (!$mqtt->connect()) {
                return json(['code' => 0, 'msg' => '连接MQTT服务器失败']);
            }
            
            // 发布消息
            $result = $mqtt->publish($topic, $message, $qos);
            
            // 断开连接
            $mqtt->disconnect();
            
            if ($result) {
                return json(['code' => 1, 'msg' => '消息发布成功', 'data' => [
                    'topic' => $topic,
                    'qos' => $qos,
                    'time' => date('Y-m-d H:i:s')
                ]]);
            } else {
                return json(['code' => 0, 'msg' => '消息发布失败']);
            }
            
        } catch (\Throwable $e) {
            return json(['code' => 0, 'msg' => '发生错误: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 发布消息页面
     */
    public function index()
    {
        return $this->fetch();
    }
} 